package org.recast4j;

import cn.hutool.core.io.FileUtil;
import org.recast4j.demo.builder.SoloNavMeshBuilder;
import org.recast4j.demo.geom.DemoInputGeomProvider;
import org.recast4j.demo.io.ObjImporter;
import org.recast4j.detour.MeshData;
import org.recast4j.detour.NavMesh;
import org.recast4j.detour.io.MeshSetWriter;
import org.recast4j.my.NavMeshConf;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteOrder;

/**
 * TODO
 *
 * @author 司云龙
 * @version 1.0
 * @date 2022/1/20 16:01
 */
public class CreateMeshMain {
    public static void main(String[] args) {
//        String name = args[0];
        NavMeshConf.MaxPoly = Math.max(6, Integer.parseInt(args[0]));
        NavMeshConf.m_vertsPerPoly = NavMeshConf.MaxPoly;

//        NavMeshConf.m_cellSize = Math.max(0.3f, Float.parseFloat(args[1]));
//        NavMeshConf.m_cellHeight = NavMeshConf.m_cellSize;

        String path= "./game.obj";
        long now = System.currentTimeMillis();
        System.out.println("v开始加载 : poly:"+NavMeshConf.MaxPoly);
        NavMesh navMesh = new NavMesh(build(path), NavMeshConf.MaxPoly, 0);
        readFile(navMesh,"./game.navmesh");
        System.out.println("v结束加载"+(System.currentTimeMillis()-now));

    }

    public static MeshData build(String filename) {
//        String filename = "F:\\1000.obj";
        InputStream stream = null;
        try {
            SoloNavMeshBuilder soloNavMeshBuilder = new SoloNavMeshBuilder();
            stream = FileUtil.getInputStream(filename);
            DemoInputGeomProvider geom = new ObjImporter().load(stream);
            MeshData meshData = soloNavMeshBuilder.build(geom);
//            System.out.println(new Gson().toJson(meshData));
            return meshData;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void readFile(NavMesh navMesh, String path) {
        OutputStream outputStream = null;
        try {
            FileUtil.del(path);
            outputStream = FileUtil.getOutputStream(path);
            MeshSetWriter meshSetWriter = new MeshSetWriter();
            meshSetWriter.write(outputStream, navMesh, ByteOrder.BIG_ENDIAN, true);

        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
